package cn.gogetter;

import java.io.File;

import weka.classifiers.meta.FilteredClassifier;
import weka.classifiers.trees.J48;
import weka.core.Instances;
import weka.core.converters.ArffLoader;
import weka.filters.unsupervised.attribute.Remove;
/**
 * 即时过滤
 */
public class FilteringOnTheFly {
	public static void main(String[] args){
		ArffLoader arffloader = new ArffLoader();
		Instances train = null;
		Instances test = null;
		String path = new File("").getAbsolutePath()+"\\data\\";
		System.out.println("======"+path);
		try {
			arffloader.setSource(new File(path + "segment-challenge.arff"));
			train = arffloader.getDataSet();
			arffloader.setSource(new File(path + "segment-test.arff"));
			test = arffloader.getDataSet();
			// 设置类别属性
			train.setClassIndex(train.numAttributes() - 1);
			test.setClassIndex(test.numAttributes() - 1);
			// 检查训练集和测试集是否兼容
			if(!train.equalHeaders(test))
				throw new Exception("训练集和测试集不兼容：\n" + train.equalHeadersMsg(test));
			// 过滤器
			Remove rm = new Remove();
			rm.setAttributeIndices("1");
			// 分类器
			J48 j48 = new J48();
			j48.setUnpruned(true);
			
			// 元分类器
			FilteredClassifier fc = new FilteredClassifier();
			fc.setFilter(rm);
			fc.setClassifier(j48);
			
			// 训练并预测
			fc.buildClassifier(train);
			for(int i = 0;i < test.numInstances(); i++){
				double pred = fc.classifyInstance(test.instance(1));
				System.out.println("编号：" + (i + 1));
				System.out.println("，实际类别：" + test.classAttribute().value((int)pred));
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
